/*
 Copyright (C) 2010 Chris Hawkins. All rights reserved.
 
 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:
 
 * Redistributions of source code must retain the above copyright notice, this
 list of conditions and the following disclaimer.
 
 * Neither the name of the author nor the names of its contributors may be used
 to endorse or promote products derived from this software without specific
 prior written permission.
 
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#import "AsdSignatureProvider.h"
#import "AsdConst.h"
#import "AsdRequest.h"
#import "AsdUtil.h"

@implementation ASDCfSignatureProvider
#pragma mark -- NSObject standard
- (id)                          initWithName: (NSString*) _name access: (NSString*) _accessKey secret: (NSString*) _secretKey {
    self = [super init];
    if ( self != nil ) {
        uniquePublicName    = [_name        retain];
        accessKeyID         = [_accessKey   retain];
        secretAccessKey     = [_secretKey   retain];
    }
    return self;
}
- (void)                        dealloc {
    [uniquePublicName   release];
    [accessKeyID        release];
    [secretAccessKey    release];
    [super dealloc];
}
#pragma mark -- ASD_SignatureProvider
- (NSString*)                   uniquePublicName {
    return uniquePublicName;
}
- (NSString*)                   accessKeyID {
    return accessKeyID;
}
- (NSString*)                   requestSignature: (NSMutableDictionary*) requestParameters_  
                                            verb: (NSString*) httpVerb_
                                            host: (NSString*) hostName_
                                          signed: (NSMutableString*) signedString_ 
{
    NSMutableString *signedStr = ( signedString_ != nil ? [signedString_ retain] : [[NSMutableString alloc] initWithCapacity: 1000] );
    
    // Specify how we are creating the signature
    [requestParameters_ setValue: [ASDSpConst rqvSignatureMethod]  forKey: [ASDSpConst rqpSignatureMethod]];
    [requestParameters_ setValue: [ASDSpConst rqvSignatureVersion] forKey: [ASDSpConst rqpSignatureVersion]];
    
    NSString *verbUpperC  = [[httpVerb_ uppercaseString] retain];  
    NSString *hostLowerC  = [[hostName_ lowercaseString] retain];
    NSString *queryString = [[ASDRqBase sortedQueryString: requestParameters_ encode: TRUE] retain];
    [signedStr appendString: verbUpperC];
    [signedStr appendString: @"\n"];
    [signedStr appendString: hostLowerC];
    [signedStr appendString: @"\n/\n"];
    [signedStr appendString: queryString];
    
    NSData   *digest      = [[ASDSpUtil hmacSHA256withKey: secretAccessKey forString: signedStr] retain];
    
    NSString *signature   = [[ASDSpUtil base64forData: digest] retain];    
    
    [verbUpperC  release];
    [hostLowerC  release];
    [digest      release];
    [queryString release];
    [signedStr   release];
    return [signature autorelease];
}
#pragma mark -- class methods: Collection
+ (NSMutableDictionary*)        providerDictionary {
    static NSMutableDictionary* dict    = nil;
    if ( dict == nil ) {
        @synchronized( self ) {
            if ( dict == nil ) {
                dict = [[NSMutableDictionary alloc] initWithCapacity: 8];
            }
        }
    }
    return dict;
}
+ (void)                        addProvider: (ASDCfSignatureProvider*)provider {
    NSMutableDictionary  *dict = [[self providerDictionary] retain];
    @synchronized( dict ) {
        [dict setObject: provider forKey: [provider uniquePublicName]];
    }
    [dict release];
}
+ (BOOL)                        removeProvider: (NSString*) providerName {
    NSMutableDictionary  *dict    = [[self providerDictionary] retain];
    BOOL                  removed = FALSE;
    @synchronized( dict ) {
        if ( nil != [dict objectForKey: providerName] ) {
            [dict removeObjectForKey: providerName];
            removed = TRUE;
        }
    }
    [dict release];
    return removed;
}
+ (ASDCfSignatureProvider*)       getProvider: (NSString*) providerName {
    NSMutableDictionary  *dict = [[self providerDictionary] retain];
    ASDCfSignatureProvider *prov = nil;
    @synchronized( dict ) {
        prov = [[dict objectForKey: providerName] retain];
    }
    [dict release];
    return [prov autorelease];
}
+ (NSDictionary*)               getAllProvider {
    return [self providerDictionary];
}
+ (void)                        clearAllProvider {
    NSMutableDictionary  *dict = [[self providerDictionary] retain];
    @synchronized( dict ) {
        [dict removeAllObjects];
    }
    [dict release];
}

#pragma mark -- class methods: Invalid and random logic 
+ (NSString*)                   invalidProviderName {
    return @"Invalid";
}
+ (ASDCfSignatureProvider*)       invalidProvider {
    ASDCfSignatureProvider* invalid = [[ASDCfSignatureProvider alloc] initWithName: [self invalidProviderName]
                                                                            access: [self randomAccessKeyID] 
                                                                            secret: [self randomSecretAccessKey]];
    return [invalid autorelease];
}
+ (NSString*)                   randomAccessKeyID {
    return [self randomString: 20 characters: @"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"];
}
+ (NSString*)                   randomSecretAccessKey {
    return [self randomString: 40 characters: @"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz+"];
}
+ (NSString*)                   randomString: (NSUInteger) _length characters: (NSString*) _validCharacters {
    NSMutableString* buffer  = [[NSMutableString alloc] initWithCapacity: _length];
    NSUInteger       divRand = [_validCharacters length] -1;
    for ( NSUInteger count = 0; count < _length; count++) {
        NSUInteger index = ( arc4random() % divRand );
        [buffer appendFormat: @"%C", [_validCharacters characterAtIndex: index]];
    }
    NSString*        key     = [[NSString alloc] initWithString: buffer];
    [buffer release];
    return [key autorelease];
}
@end
